package it.java.giw.solr;

import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;

/**
 * il metodo getSuggestion e getHighlightings sono inciso nella roccia! 
 * PRIMA DI MODIFICARE FARE UNA COPIA DI BACKUP O NON PUSHARE SOPRA
 * TODO:
 * - facet --> ELEFANTE E' TUTTA TUA
 */
public class DemoSearch {

	public void search(String queryStrings) throws MalformedURLException, SolrServerException {
		if (queryStrings != null &&  !queryStrings.isEmpty()) { 

			try {
				SolrServer server = new HttpSolrServer("http://localhost:8983/solr");
				ModifiableSolrParams params = new ModifiableSolrParams();
				params.set("qt", "/browse");
				params.set("spellcheck", "true");
				params.set("spellcheck.collate", "true");
//				System.out.println(params);
				SolrQuery query = new SolrQuery();
				query.setQuery(queryStrings);
				query.add(params);
				
				QueryResponse response = server.query(query);
				//NOTA: l'ordine di queste due istruzioni e' importante!!
				response = getSuggestions(queryStrings, server, response);
				getHighlightings(response);				
				
				System.out.println("Elenco risultati:");
				SolrDocumentList results = response.getResults();
				for (int i = 0; i < results.size(); i++)
					System.out.println(results.get(i).getFieldValue("title"));
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	private void getHighlightings(QueryResponse response) {
		Map<String, Map<String, List<String>>> mappina = response.getHighlighting();
		for(String key : mappina.keySet()){
			System.out.println(key);
			Map<String, List<String>> mappetta = mappina.get(key);
			for(String secondaryKey : mappetta.keySet()){
				System.out.print(secondaryKey + "-->");
				for(String snippet : mappetta.get(secondaryKey))
					System.out.println(snippet);
			}
		}
	}

	private QueryResponse getSuggestions(String queryStrings,
			SolrServer server, QueryResponse response)
			throws SolrServerException {
		boolean found;
		SpellCheckResponse scr = null;
		String collated ="";
		if(response != null){
			scr = response.getSpellCheckResponse();
			if(scr != null){
				List<Suggestion> suggLst = scr.getSuggestions();
				if (suggLst.isEmpty())
					System.err.println("Empty suggestions");
				queryStrings = queryStrings.toLowerCase();
				StringTokenizer tokenizer = new StringTokenizer(queryStrings);
				while (tokenizer.hasMoreTokens()){
					found = false;
					String token = tokenizer.nextToken();
					if (suggLst.isEmpty())
						collated = queryStrings;
					else{
						for (Suggestion sugg : suggLst){
							if (token.equals(sugg.getToken())){
								collated = collated.concat(sugg.getAlternatives().get(0)+" ");
								found = true;
								break;
							}
						}
						if (!found)
							collated = collated.concat(token+" ");
					}
				}
				for(Suggestion sugg : suggLst){
					System.out.println("There are "+ sugg.getNumFound() +" suggestion for token '"+sugg.getToken()+"' are: ");
					System.out.println(sugg.getAlternatives());
				}
				System.out.println("Forse intendevi: "+ collated);
			}
		}
		System.out.println("oppure cerca quello che volevi cercare:"+queryStrings);
		
		SolrQuery queryCollated = new SolrQuery(collated+boost(collated));
		queryCollated.setHighlight(true);
		queryCollated.setHighlightSnippets(3);
		queryCollated.addHighlightField("description");
//		query.addHighlightField("content");
		response = server.query(queryCollated);
		return response;
	}

	private String boost(String collated) {
		String boostedPhraseQuery = " OR \""+collated+"\"^150";
		return boostedPhraseQuery;
	}

}